<?php
/**
 * ===============================================
 * 版权所有 2019-2050 青岛铁锤科技有限公司，并保留所有权利。
 * 网站地址: http://www.huaxianling.com
 * ===============================================
 * Author: Happy dong
 * Created Time: 2019-06-29 09:12
 * Modified Time: 2019-06-29 11:24
 * Version: 2.0
 */

namespace App\Modules\Order\Repositories;


use App\Exceptions\AllValidatorException;
use App\Exceptions\NotFoundException;
use App\Lib\Utilities;
use App\Models\OrderComment;
use App\Modules\Order\Criterias\getCommentListCriteria;
use App\Modules\Order\Criterias\getOrderCommentResourceCriteria;
use App\Modules\Order\Validators\OrderCommentValidator;
use Flower\Core\Repository\Eloquent\BaseRepository;
use Flower\Core\Repository\Exceptions\ValidatorException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\MessageBag;

class OrderCommentRepository extends BaseRepository
{
    public function model()
    {
        return OrderComment::class;
    }

    public function validator()
    {
        return OrderCommentValidator::class;
    }

    /**
     * 订单评论
     * @param $requestData
     * @return mixed
     * @throws NotFoundException
     */
    public function add($requestData)
    {
        // 查询该订单的信息是否存在
        $orderInfo = (new OrderRepository())->isExisted($requestData['order_id']);
        // 查询该订单是不是该用户的
        if ($orderInfo->member_id != $requestData['member_id']) {
            throw  new NotFoundException(['msg' => '评论订单不是你自己的！']);
        }
        // 查询该订单是否已经付款完成
        if (!$orderInfo->is_pay && ($orderInfo->status == config('constant.orderStatus')['done'])) {
            throw  new NotFoundException(["msg" => "该订单还未完成，请完成后评价！"]);
        }
        /**
         * 评论资源上传处理
         */
        $resourceInfo = $requestData['img'];
        //开启事务
        DB::beginTransaction();
        // 插入评论
        $commentInfo = $this->addComment($orderInfo, $requestData);
        // 插入评论资源
        $res = (new CommentResourceRepository())->insertData($commentInfo, $resourceInfo);
        // 修改订单状态
        $orderInfo->status = config('constant.orderStatus')['comment'];
        $orderInfo->save();
        $res ? DB::commit() : DB::rollBack();
        return $res;
    }

    /**
     *  插入新的订单评论
     * @param $orderId
     * @param $barberId
     * @param $storeId
     * @param $memberId
     * @param $comment
     * @param $scoreAttitude
     * @param $scoreSkill
     * @param $scoreAppearance
     * @param $scoreStore
     * @param $waitingTime
     * @return mixed
     */
    public function addComment($orderId, $barberId, $storeId, $memberId, $comment, $scoreAttitude, $scoreSkill, $scoreAppearance, $scoreStore, $waitingTime)
    {

        $data = [
            'order_id' => $orderId,
            'store_id' => $storeId,
            'user_id' => $barberId,
            'member_id' => $memberId,
            'comment' => $comment,
            'score_attitude' => $scoreAttitude,
            'score_store' => $scoreStore,
            'waiting_time' => $waitingTime,
            'score_appearance' => $scoreAppearance,
            'score_skill' => $scoreSkill,
            'is_goods' => $scoreStore > 6 ? 1 : 0
        ];
        return $this->create($data);
    }

    /**
     * 检测评论是否存在
     * @param $commentId
     * @return mixed
     * @throws NotFoundException
     * @author Happy dong
     * @modifiedTime 2019-07-31 17:34
     */
    public function isExisted($commentId)
    {
        $comment = $this->find($commentId);
        if (empty($comment)) {
            throw new NotFoundException(['msg' => "评论不存在"]);
        }
        return $comment;
    }


    /**
     * 店铺/理发师某天的好评个数
     * @param $storeId
     * @param int $userId 0 查询店铺 其它查询理发师
     * @param string $date 默认今天
     * @return string
     */
    public function getCommentGoodRate($storeId, $userId = 0, $date = '')
    {
        $map = empty($userId) ? ['store_id' => $storeId] : ['store_id' => $storeId, 'user_id' => $userId];
        $date = empty($date) ? date('Y-m-d', time()) : $date;
        $list = $this->model->where($map)->whereDate('created_at', $date)->get()->toArray();
        $rate = '0.00%';
        if (!empty($list)) {
            $newList = Utilities::arrayColumnGroup($list, null, 'is_goods');
            $rate = (round(count($newList[1]) / count($list), 4) * 100) . '%';
        }
        return $rate;
    }


    /**
     * 获取订单评论
     * 一个订单只有一条评论确定过
     * Modified Time : 2019-07-12 09:34
     * @param $requestData
     * @return string
     */
    public function getOrderComment($requestData)
    {

        $dataImg = ['where' => ['order_id' => $requestData['order_id'],
            'member_id' => $requestData['member_id']
        ],

            'type' => 1];
        $dataVideo = ['where' => ['order_id' => $requestData['order_id'],
            'member_id' => $requestData['member_id']],
            'type' => 2];
        $Imgs = $this->getByCriteria(new getOrderCommentResourceCriteria($dataImg))->first()->toArray();

        $Videos = $this->getByCriteria(new getOrderCommentResourceCriteria($dataVideo))->first()->toArray();

        if (!empty($Imgs['resource'])) {
            $resourceImgs = $Imgs['resource'];
            unset($Imgs['resource']);
        }
        $newData = $Imgs;
        $newData['imgList'] = Utilities::dataFormat($resourceImgs, 'picture');
        $newData['video'] = Utilities::dataFormat($Videos['resource'], 'video');
        return $newData;
    }

    /**
     * 删除订单评论
     * @param $requestData
     * @return int
     * @throws ValidatorException
     */
    public function delete($requestData)
    {
        $ids = isset($requestData['id']) ? $requestData['id'] : 0;
        if (empty($ids)) {
            throw new AllValidatorException(['msg'=>'被删除的订单评论ID不能为空']);
        }
        return $this->model::destroy($ids);
    }

    /**
     * 查看次数自增1
     * @param $commentId
     * @return mixed
     */
    public function viewTimesSetInc($commentId)
    {
        return $this->model->where(['id' => $commentId])->increment('view_times');
    }

    public function getGoodOrderAmountRate($storeId, $date, $compareDate)
    {
        return $this->model
            ->selectRaw('date(created_at) as dates, count(id) as counts')
            ->whereRaw('(store_id=' . $storeId . ' and is_goods=1 and date(created_at)="' . $date . '")')
            ->orWhereRaw('(store_id=' . $storeId . ' and is_goods=1 and date(created_at)="' . $compareDate . '") group by date(created_at)')
            ->get()->toArray();
    }

    //查看理发师在某店某天评论数
    public function getBarberDateCommentNum($user_id, $store_id, $date)
    {
        return $this->model->where('user_id', $user_id)
            ->where('store_id', $store_id)
            ->whereDate('created_at','=',$date)
            ->get()
            ->count();
    }

    //计算理发师在某店某天好评率
    public function getBarberDateGoodCommentRate($user_id, $store_id, $date)
    {
        //总评论数
        $comment_num = $this->getBarberDateCommentNum($user_id, $store_id, $date);

        //好评数
        $goods_comment_num = $this->model->where('user_id', $user_id)
            ->where('store_id', $store_id)
            ->whereDate('created_at','=',$date)
            ->get()
            ->count();

        $goods_comment_rate = $comment_num == 0 ? 0 : $goods_comment_num / $comment_num;

        return $goods_comment_rate;
    }


	/**
	 * 获取理发师评论列表
	 * @param $storeId
	 * @param $barberId
	 * @param $orderId
	 * @param $pageSize
	 * @param $memberId
	 * @return mixed
	 * @throws \Flower\Core\Repository\Exceptions\RepositoryException
	 */
    public function getBarberListComment($storeId,$barberId,$orderId,$pageSize,$memberId){
    	return $this->pushCriteria(new getCommentListCriteria($storeId,$barberId,$orderId,$memberId))->paginate($pageSize, ['*'], 'paginate');
    }


    public function getBarberCommentScore($storeId,$userId){
       $stores = $this->model->where(['store_id'=>$storeId,'user_id'=>$userId])->average('score_store');
       if(empty($stores)) $stores = 10;
       return round($stores,1);
    }
}